﻿namespace Common
{
    /// <summary>
    /// string 转成number的扩展帮助类
    /// </summary>
    public static class StringConvertToNumberHelper
    {
        /// <summary>
        /// string convert to int32
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int ToInt32(this string str, int defaultValue = 0)
        {
            int temp;
            return int.TryParse(str, out temp) ? temp : defaultValue;
        }
        /// <summary>
        /// string convert to int64
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static long ToInt64(this string str, long defaultValue = 0)
        {
            long temp;
            return long.TryParse(str, out temp) ? temp : defaultValue;
        }
        /// <summary>
        /// string convert to double
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static double ToDouble(this string str, double defaultValue = 0)
        {
            double temp;
            return double.TryParse(str, out temp) ? temp : defaultValue;
        }
        /// <summary>
        /// string convert to decimal
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this string str, decimal defaultValue = 0)
        {
            decimal temp;
            return decimal.TryParse(str, out temp) ? temp : defaultValue;
        }
        /// <summary>
        /// str convert to bool
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool ToBool(this string str)
        {
            bool temp;
            return bool.TryParse(str, out temp) && temp;
        }
    }
}
